<?php

namespace app\admin\controller;

use think\Db;
use think\facade\Request;
use clt\Form;
use service\DataService;
use service\ToolsService;
use service\LogService;
use think\Cache;
use think\Paginator;

class Pros extends Common{

    protected  $dao,$fields;

    public function _initialize()
    {
        parent::_initialize();
        // $pros = $this->_get_random_dscp();
        // halt($pros);
    }

    //获取随机分类电商产品
    public function _get_random_dscp($aid = 1, $keyword = null, $page = 1, $limit = 20){
        $catMap = [];
        $dscats = Db::name('Category')->where($catMap)->order('id desc, sort desc')->column('id,catname,module,moduleid');
        $aids = $this->_getAIDs($aid);
        $dscpMap['aid'] = ['in', $aids];
        $dscpMap['status'] = 1;
        // $dscpMap['pic'] = ['neq', ""];
        $dsD = $dsDv = $dsDa = [];
        // halt($dscats);
        foreach ($dscats as $k => $v) {
            $vmap  = $amap = $dsDitem = [];
            $vmap  = $amap = $dscpMap;
            $msysfields = [
                'title',
                'content',
            ];
            $mfields = Db::name('field')->where(['moduleid' => $v['moduleid'], 'status' => 1, 'isshow' => 1])->column('field');
            if($mfields){
                $msysfields = array_merge($msysfields, $mfields);
            }
            $mfd = join('|', $msysfields);
            if($keyword){//关键字查询
                if($msysfields){
                    $vmap["$mfd"] = ['like', "%".$keyword."%"];                    
                }else{
                    continue;
                }
                $dsDitem = Db::name($v['module'])->where($vmap)->order('id desc, sort desc')->select();
                if(!$dsDitem)continue;
                foreach ($dsDitem as $kk => $vv) {
                    $dsDitem[$kk]['moduleid'] = $v['moduleid'];
                    $dsDitem[$kk]['catid'] = $v['id'];
                    if(null !== $dsDv){
                        array_push($dsDv, $dsDitem[$kk]);
                    }else{
                        $dsDv[] = $dsDitem[$kk];
                    }
                }
                $dsD = $dsDv;
                // $dsD = array_slice($dsDv, $page-1, $limit);
            }else{
                $dsDitem = Db::name($v['module'])->where($amap)->order('id desc, sort desc')->select();
                if(!$dsDitem)continue;
                foreach ($dsDitem as $kk => $vv) {
                    $dsDitem[$kk]['moduleid'] = $v['moduleid'];
                    $dsDitem[$kk]['catid'] = $v['id'];
                    if(null !== $dsDa){
                        array_push($dsDa, $dsDitem[$kk]);
                    }else{
                        $dsDa[] = $dsDitem[$kk];
                    }
                }
                $dsD = $dsDa;
                // $dsD = array_slice($dsDa, $page-1, $limit);
            }
        }
        return $dsD;
    }

    //根据地区id获取所有ids
    public function _getAIDs($aid = 1){
        if(Cache::get($aid.'_ids')){
            return Cache::get($aid.'_ids');
        }

        if(Cache::get('areas')){
            $areas = Cache::get('areas');
        }else{
            $areas = db::connect(config('dbx.SU'))->name('area')->where(['area_open' => 1])->select();
            Cache::set('areas', $areas, 3600);
        }
        $all_ids = ToolsService::getArrSubIds($areas,$aid,'area_id','area_parent_id');//当前区域下地区Ids

        // $all_ids = $this->area->getAllAreaSubIds($aid);
        
        Cache::set($aid.'_ids', $all_ids, 3600);
        // halt(Cache::set($aid.'_ids'));
        return $all_ids;
    }

    public function index(){
        if(request()->isPost()){
            // halt(input(''));
            $keyword=input('post.title');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $order = "id desc, sort desc";


            $aid = (input('county') ? input('county') : (input('city') ? input('city') : (input('province') ? input('province') : (input('aid') ? input('aid') : session('user.aid')))));
            // halt($aid);
            // $aids = ToolsService::getArrSubIds($this->areaList,$aid,'area_id','area_parent_id');
            // $map['aid'] = ['in', $aids];
            // $map['status'] = 1;
            // halt($this->aids);
            
            // $dscats = Db::name('Category')->where($catMap)->order('sort desc')->column('module');
            // $list = Db::table(implode(',',$dscats))
            //     ->where($map)
            //     ->order($order)
            //     ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
            //     ->toArray();
            // $lists = $this->_get_random_dscp($aid, $keyword, $page, $pageSize);
            
            //自定义分页：1查出所有的数据 2根据每页数量进行分页3返回分页数据data
            $lists = $this->_get_random_dscp($aid, $keyword);
            foreach ($lists as $k=>$v ){
                $lists[$k]['module'] =get_model_value($v['catid'], 'Category', 'module');
                $lists[$k]['catname'] = get_model_value($v['catid'],'Category', 'catname');
                $lists[$k]['area_name'] = join_area_name($v['aid']);
                $lists[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
            }
            // halt($lists);
            $dataTo=array_chunk($lists, $pageSize);
            $data = $dataTo[$page-1];
            $result['code'] = 0;
            $result['msg'] = "获取成功";
            $result['data'] = $data;
            $result['count'] = count($lists);
            $result['rel'] = 1;
            $result['province'] = $this->_getPid(['area_parent_id' => 1], (input('province') ? input('province') : session('user.aid')));
            $result['city'] = $this->_getPid(['area_parent_id' => (input('province') ? input('province') : session('user.aid'))], input('city'));
            $result['county'] = $this->_getPid(['area_parent_id' => input('city')], input('county'));
            // halt($result);
            return $result;
        }else{
            return $this->fetch ('pros/index');
        }
    }

    public function edit(){
        $id = input('id');
            // $request = Request::instance();
            $request = request();
        $controllerName = $request->controller();
        if($controllerName=='Page'){
            $p = $this->dao->where('id',$id)->find();
            if(empty($p)){
                $data['id']=$id;
                $data['title'] = $this->categorys[$id]['catname'];
                $data['keywords'] = $this->categorys[$id]['keywords'];
                $this->dao->insert($data);
            }
        }
        $info = $this->dao->where('id',$id)->find();


        if($this->aDeep > 2 && !empty($this->fields)){
            unset($info['status']);
        }
        
        $form=new Form($info);
        $returnData['vo'] = $info;
        $returnData['form'] = $form;
        // halt($this->fields);
        $push = isset($info['push']) ? $info['push'] : '';
        $info['push'] = explode(',', $push);
        $pos = config('dbx.push');
        $this->assign ('pos', $pos );
        $this->assign ('info', $info );
        $this->assign ( 'form', $form );
        $this->assign ( 'title', '编辑内容' );

        $cid = request()->param('catid');
        $pcid = db('category')->where(['id' => $cid])->value('parentid');
        $this->assign ('catid', $this->catid);

        return $this->fetch('content/edit');
    }

    function update(){
            // $request = Request::instance();
            $request = request();

        $controllerName = $request->controller();
        $model = $this->dao;
        $fields = $this->fields;
        $post = $request->except('file');
        // array_shift($post);
        // halt($fields);
        $data = $this->checkfield($fields, $post);
        if (isset($data['push']) && is_array($data['push'])) {
            $data['push'] = join(',', $data['push']);
        }else{
            $data['push'] = '';
        }
        if(isset($data['code'])){
            return ['code'=>0,'msg'=>$data['msg']];
        }

        if(isset($fields['updatetime'])) {
            $data['updatetime'] = time();
        }

        //关键字检测
        if(ckWord($data['title'])){
            return ['code'=>0,'msg'=>'标题包含敏感词：'.'"'.ckWord($data['title']).'"'];
        }
        if(ckWord($data['keywords'])){
            return ['code'=>0,'msg'=>'关键字包含敏感词：'.'"'.ckWord($data['keywords']).'"'];
        }
        if(ckWord($data['description'])){
            return ['code'=>0,'msg'=>'简介包含敏感词：'.'"'.ckWord($data['description']).'"'];
        }
        if(ckWord($data['content'])){
            return ['code'=>0,'msg'=>'内容包含敏感词：'.'"'.ckWord($data['content']).'"'];
        }

        $title_style ='';
        if (isset($data['style_color'])) {
            $title_style .= 'color:' . $data['style_color'].';';
            unset($data['style_color']);
        }else{
            $title_style .= 'color:#222;';
        }
        if (isset($data['style_bold'])) {
            $title_style .= 'font-weight:' . $data['style_bold'].';';
            unset($data['style_bold']);
        }else{
            $title_style .= 'font-weight:normal;';
        }
        if($fields['title']['setup']['style']==1) {
            $data['title_style'] = $title_style;
        }
        if($controllerName!='Page') {
            $data['updatetime'] = time();
        }
        // unset($data['aid']);
        unset($data['pics_name']);
        //编辑多图和多文件
        foreach ($fields as $k=>$v){
            if($v['type']=='files' ){
                if(!$data[$k]){
                    $data[$k]='';
                }
                $data[$v['field']] = $data['images'];
            }
            if($v['type']=='images'){
                if(!isset($data[$k])){
                    $data[$k]='';
                }
                if($data[$k]){
                    $data[$v['field']] = implode(';',$data[$k]);
                }
            }
        }
        // halt($data);
        $list=$model->strict(false)->update($data);
        if (false !== $list) {
            if($controllerName=='Page'){
                $result['url'] = url('/').'admin.html#/admin/category/index?spm=m-166-178';
            }else{
                $controllerName = strtolower($controllerName);
                $result['url'] = url('/').'admin.html#'.url("admin/".$controllerName."/index",['catid'=>$data['catid']]).'?spm=m-166-178';
                // $result['url'] = url("admin.html#/admin/".$controllerName."/index",array('catid'=>$data['catid']));
            }
            LogService::write('系统内容', '内容修改成功');
            $result['msg'] = '修改成功!';
            $result['code'] = 1;
            return $result;
        } else {
            $result['msg'] = '修改失败!';
            $result['code'] = 0;
            return $result;
        }
    }
    
    //设置审核状态
    public function editState(){
        $id=input('post.id');
        $status=input('post.status');
        if($this->dao->where('id='.$id)->update(['status'=>$status])!==false){
            LogService::write('系统内容', '内容状态修改成功');
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }

    //批量审核
    public function statusAll(){
        $map['id'] =array('in',input('post.ids/a'));
        $model = $this->dao;
        $model->where($map)->update(['status'=>1]);
        $result['code'] = 1;
        $result['msg'] = '审核成功！';
        $result['url'] = url('index',array('catid'=>$this->catid));
        LogService::write('系统内容', '内容批量审核成功');
        return $result;
    }

    //取消批量审核
    public function statusCancelAll(){
        $map['id'] =array('in',input('post.ids/a'));
        $model = $this->dao;
        $model->where($map)->update(['status'=>0]);
        $result['code'] = 1;
        $result['msg'] = '取消审核成功！';
        $result['url'] = url('index',array('catid'=>$this->catid));
        LogService::write('系统内容', '内容批量取消审核成功');
        return $result;
    }

    //设置提取状态
    public function editPush(){
        $id=input('post.id');
        $push=input('post.push');
        $val = switchArDeep(session('user.aid'));
        if(!$val)return ['status'=>0,'msg'=>'设置失败!'];
        if($this->dao->where('id='.$id)->update(["$val"=>$push])!==false){
            LogService::write('系统内容', '内容提取成功');
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }

    //批量提取
    public function pushAll(){
        $map['id'] =array('in',input('post.ids/a'));
        $val = switchArDeep(session('user.aid'));
        $model = $this->dao;
        $model->where($map)->update(["$val"=>1]);
        $result['code'] = 1;
        $result['msg'] = '提取成功！';
        $result['url'] = url('index',array('catid'=>$this->catid));
        LogService::write('系统内容', '内容批量提取成功');
        return $result;
    }

    //取消批量提取
    public function pushCancelAll(){
        $map['id'] =array('in',input('post.ids/a'));
        $val = switchArDeep(session('user.aid'));
        $model = $this->dao;
        $model->where($map)->update(["$val"=>0]);
        $result['code'] = 1;
        $result['msg'] = '取消提取成功！';
        $result['url'] = url('index',array('catid'=>$this->catid));
        LogService::write('系统内容', '内容批量取消提取成功');
        return $result;
    }

    public function set_categorys($categorys = array()) {
        if (is_array($categorys) && !empty($categorys)) {
            foreach ($categorys as $id => $c) {
                $this->categorys[$c['id']] = $c;
                $r = db('category')->where("parentid = $c[id]")->order('listorder DESC,id DESC')->select();
                $this->set_categorys($r);
            }
        }
        return true;
    }
    function checkfield($fields,$post){
        foreach ( $post as $key => $val ) {
            if(isset($fields[$key])){
                $setup=$fields[$key]['setup'];
                if(!empty($fields[$key]['required']) && empty($post[$key])){
                    $result['msg'] = $fields[$key]['errormsg']?$fields[$key]['errormsg']:'缺少必要参数！';
                    $result['code'] = 0;
                    return $result;
                }
                if(isset($setup['multiple'])){
                    if(is_array($post[$key])){
                        $post[$key] = implode(',',$post[$key]);
                    }
                }
                if(isset($setup['inputtype'])){
                    if($setup['inputtype']=='checkbox'){
                        $post[$key] = implode(',',$post[$key]);
                    }
                }
                if(isset($setup['fieldtype'])){
                    if($fields[$key]['type']=='checkbox'){
                        $post[$key] = implode(',',$post[$key]);
                    }
                }
                if($fields[$key]['type']=='datetime'){
                    $post[$key] =strtotime($post[$key]);
                }elseif($fields[$key]['type']=='textarea'){
                    $post[$key]=addslashes($post[$key]);
                }elseif($fields[$key]['type']=='linkage'){
                    if($post[$key][0]){
                        $post[$key] = implode(',',$post[$key]);
                    }else{
                        unset($post[$key]);
                    }
                }elseif($fields[$key]['type']=='editor'){
                    if(isset($post['add_description']) && $post['description'] == '' && isset($post['content'])) {
                        $content = stripslashes($post['content']);
                        $description_length = intval($post['description_length']);
                        $post['description'] = str_cut(str_replace(array("\r\n","\t",'[page]','[/page]','&ldquo;','&rdquo;'), '', strip_tags($content)),$description_length);
                        $post['description'] = addslashes($post['description']);
                    }
                    if(isset($post['auto_thumb']) && $post['thumb'] == '' && isset($post['content'])) {
                        $content = $content ? $content : stripslashes($post['content']);
                        $auto_thumb_no = intval($post['auto_thumb_no']) * 3;
                        if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
                            $post['thumb'] = $matches[$auto_thumb_no][0];
                        }
                    }
                }
            }
        }
        return $post;
    }

    public function add(){

        $pos = config('dbx.push');
        // halt($pos);
        $this->assign ('pos', $pos );
        
        $form=new Form();
        $this->assign ( 'form', $form );
        $this->assign ( 'title', '添加内容' );
        // $cid = request()->param('catid');
        // $pcid = db('category')->where(['id' => $cid])->value('parentid');
        // $sites = $coms = [];
        // if($pcid == 1){
        //     $sites = db("zdxx")->select();
        // }elseif($pcid == 6){
        //     $coms = db("qyxx")->select();
        // }
        // // halt($this->catid);
        // $this->assign ('sites', $sites);
        // $this->assign ('coms', $coms);
        $this->assign ('catid', $this->catid);
        return $this->fetch('content/edit');
    }
    
    public function insert(){
        // $request = Request::instance();
        $request = request();
        $controllerName = strtolower($request->controller());
        $model = $this->dao;
        $fields = $this->fields;
        $post = $request->except('file');
        // array_shift($post);
        //halt($fields);
        $data = $this->checkfield($fields, $post);
        if (isset($data['push']) && is_array($data['push'])) {
            $data['push'] = join(',', $data['push']);
        }
        if(isset($data['code']) && $data['code']==0){
            return $data;
        }
        if(isset($fields['createtime'])  && !isset($data['createtime']) ){
            $data['createtime'] = time();
        }
        if(isset($fields['updatetime'])  && !isset($data['updatetime']) ) {
            $data['updatetime'] = time();
        }
        if($controllerName!='Page') {
            if (isset($fields['updatetime'])){
                $data['updatetime'] = $data['createtime'];
            }
        }

        $data['catid'] = $this->catid;
        $data['status'] = 1;
        // if (isset($data['aid'])){
            $data['aid'] = session('user.aid');
        // }
        // if (isset($data['userid'])){
            $data['userid'] = session('user.id');
        // }
        if (!isset($data['username'])){
            $data['username'] = session('user.username');
        }

        //关键字检测
        if(ckWord($data['title'])){
            return ['code'=>0,'msg'=>'标题包含敏感词：'.'"'.ckWord($data['title']).'"'];
        }
        if(ckWord($data['keywords'])){
            return ['code'=>0,'msg'=>'关键字包含敏感词：'.'"'.ckWord($data['keywords']).'"'];
        }
        if(ckWord($data['description'])){
            return ['code'=>0,'msg'=>'简介包含敏感词：'.'"'.ckWord($data['description']).'"'];
        }
        if(ckWord($data['content'])){
            return ['code'=>0,'msg'=>'内容包含敏感词：'.'"'.ckWord($data['content']).'"'];
        }
        // halt($data);
        $title_style ='';
        if (isset($data['style_color'])) {
            $title_style .= 'color:' . $data['style_color'].';';
            unset($data['style_color']);
        }else{
            $title_style .= 'color:#222;';
        }
        if (isset($data['style_bold'])) {
            $title_style .= 'font-weight:' . $data['style_bold'].';';
            unset($data['style_bold']);
        }else{
            $title_style .= 'font-weight:normal;';
        }
        if($fields['title']['setup']['style']==1) {
            $data['title_style'] = $title_style;
        }

        unset($data['style_color']);
        unset($data['style_bold']);
        unset($data['pics_name']);
        //编辑多图和多文件
        foreach ($fields as $k=>$v){
            if($v['type']=='files' ){
                if(!$data[$k]){
                    $data[$k]='';
                }
                $data[$v['field']] = $data['images'];
            }
            if($v['type']=='images'){
                if(!isset($data[$k])){
                    $data[$k]='';
                }
                if($data[$k]){
                    $data[$v['field']] = implode(';',$data[$k]);
                }
            }
        }
        // halt($data);
        $id= $model->insertGetId($data);

        if ($id !==false) {
            if($controllerName=='page'){
                //$result['url'] = url("admin/category/index");
                $result['url'] = url('/').'admin.html#/admin/category/index?spm=m-166-178';
            }else{
                // $result['url'] = url("admin/".$controllerName."/index",array('catid'=>$data['catid']));
                $result['url'] = url('/').'admin.html#'.url("admin/".$controllerName."/index",['catid'=>$data['catid']]).'?spm=m-166-178';
            }
            LogService::write('系统内容', '内容添加成功');
            $result['msg'] = '添加成功!';
            $result['code'] = 1;
            return $result;
        } else {
            $result['msg'] = '添加失败!';
            $result['code'] = 0;
            return $result;
        }

    }


    public function listDel(){
        $id = input('post.id');
        $catid = input('catid');
        if(!$catid){            
            $result['msg'] = '参数错误!';
            $result['code'] = 0;
        }
        $module =get_model_value($catid, 'Category', 'module');
        // halt($module);
        Db::name($module)->where(array('id'=>$id))->delete();//转入回收站
        LogService::write('系统内容', '内容批量删除成功');
        return ['code'=>1,'msg'=>'删除成功！'];
    }
    public function delAll(){
        $map['id'] =array('in',input('post.ids/a'));
        $model = $this->dao;
        $model->where($map)->delete();
        $result['code'] = 1;
        $result['msg'] = '删除成功！';
        $result['url'] = url('index',array('catid'=>$this->catid));
        LogService::write('系统内容', '内容删除成功');
        return $result;
    }
    public function listorder(){
        $controllerName = strtolower($this->request->controller());
        $data = input('post.');
        $catid = input('catid');
        if(!$catid){            
            $result['msg'] = '参数错误!';
            $result['code'] = 0;
        }
        $module =get_model_value($catid, 'Category', 'module');
        // halt($module);
        Db::name($module)->update($data);
        //$result = ['msg' => '排序成功！','url'=>url('index',array('catid'=>$catid)), 'code' => 1];
        $result = ['msg' => '排序成功！','url'=>url('/').'admin.html#'.url("admin/".$controllerName."/index",['catid'=>$catid]).'?spm=m-166-178', 'code' => 1];
        // $result = ['msg' => '排序成功！', 'code' => 1, 'url'=>url('/').'admin.html#/admin/category/index?spm=m-166-178'];
        LogService::write('系统内容', '内容排序成功');
        return $result;
    }

    public function delImg(){
        if(!input('post.url')){
            return ['code'=>0,'请指定要删除的图片资源'];
        }
        $file = ROOT_PATH.__PUBLIC__.input('post.url');
        if(file_exists($file) && trim(input('post.url'))!=''){
            is_dir($file) ? dir_delete($file) : unlink($file);
        }
        if(input('post.id')){
            $picurl = input('post.picurl');
            $picurlArr = explode(':',$picurl);
            $pics = substr(implode(":::",$picurlArr),0,-3);
            $model = $this->dao;
            $map['id'] =input('post.id');
            $model->where($map)->update(array('pics'=>$pics));
        }
        $result['msg'] = '删除成功!';
        $result['code'] = 1;
        return $result;
    }
    public function getRegion(){
        $Region=db("region");
        $map['pid'] = input("pid");
        $list=$Region->where($map)->select();
        return $list;
    }
}